import 'dart:convert';
import 'dart:html' as html;
import 'dart:html';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:effective/model/result_entity.dart';
import 'package:effective/model/speech_entity.dart';
import 'package:effective/service/api.dart';
import 'package:effective/utils/base_model.dart';
import 'package:effective/view_model/user_model.dart';
import 'package:effective/widget/common_dialog.dart';
import 'package:effective/widget/cos.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'dart:js' as js;

class UploadViewModel extends BaseModel {
  bool isAgain;
  bool agreeNotice = false;
  bool agreeVolunteer = false;
  String fileName = "";
  html.File file;
  SpeechVideoEntity _speechVideoEntity;

  String theme;

  //tags类型
  bool positive = false;
  bool negative = false;
  bool happyEnding = false;
  bool sadEnding = false;
  bool happyStart = false;
  bool sadStart = false;
  bool upAndDown = false;

  TextEditingController speakerName = new TextEditingController();
  TextEditingController gender = new TextEditingController();
  TextEditingController nativeLanguage = new TextEditingController();
  TextEditingController speechTitle = new TextEditingController();
  TextEditingController speechDistrict = new TextEditingController();
  TextEditingController contestTraining = new TextEditingController();
  TextEditingController speechLevel = new TextEditingController();
  TextEditingController speechRank = new TextEditingController();
  TextEditingController speechTheme = new TextEditingController();
  TextEditingController speechTags = new TextEditingController();

  void changePositive() {
    positive = !positive;
    notifyListeners();
  }

  void changeNegative() {
    negative = !negative;
    notifyListeners();
  }

  void changeHappy() {
    happyEnding = !happyEnding;
    notifyListeners();
  }

  void changeSadEnding() {
    sadEnding = !sadEnding;
    notifyListeners();
  }

  void changeHappyStart() {
    happyStart = !happyStart;
    notifyListeners();
  }

  void changeSadStart() {
    sadStart = !sadStart;
    notifyListeners();
  }

  void changeUpAndDown() {
    upAndDown = !upAndDown;
    notifyListeners();
  }

  void changeNoticeState(bool value) {
    agreeNotice = value;
    notifyListeners();
  }

  void changeVolunteer(bool value) {
    agreeVolunteer = value;
    notifyListeners();
  }

  void changeTheme(String value) {
    theme = value;
    notifyListeners();
  }

  UploadViewModel({API api}) : super(api: api);

  Future<void> logout(BuildContext context) {
    showDialog(
        context: (context),
        builder: (context) {
          return AlertDialog(
            content: Container(
              child: Text('确认要退出登录吗？'),
            ),
            actions: [
              TextButton(
                  onPressed: () async {
                    ResultEntity resultEntity =
                        await api.logout(context.read<UserModel>().token);
                    if (resultEntity.code == 200) {
                      context.read<UserModel>().update("");
                    } else {
                      Fluttertoast.showToast(msg: resultEntity.message);
                    }
                    Navigator.pop(context);
                  },
                  child: Text('确认')),
              TextButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: Text('取消')),
            ],
          );
        });
  }

  Future<void> login(BuildContext context) async {
    ResultEntity resultEntity = await CommonDialog().loginDialog(context);

    if (resultEntity != null) {
      context.read<UserModel>().update(resultEntity.data['username']);
      context.read<UserModel>().token = resultEntity.data['token'];
      notifyListeners();
      loadData(context);
    }
  }

  Future<void> chooseFile() async {
    /*   FilePickerResult result =
        await FilePicker.platform.pickFiles(type: FileType.media,);
    if (result != null) {
      print(fileName);

      file = await MultipartFile.fromFile(result.files.single.path,filename: result.files.single.name);
      //result.files.single.bytes;
      //File file = File(result.files.single.bytes, result.files.single.name);
      //MultipartFile file = await MultipartFile.fromFile(result.files.single.path);
      fileName = result.files.single.name;

    }*/
    html.InputElement uploadInput = html.FileUploadInputElement();
    uploadInput.draggable = true;
    uploadInput.click();
    uploadInput.multiple = false;
    uploadInput.onChange.listen((e) {
      final files = uploadInput.files;
      file = files[0];
      fileName = file.name;
      notifyListeners();
    });

    notifyListeners();
  }

  Future submit(BuildContext context) async {
    if (!(agreeNotice && agreeVolunteer)) {
      showDialog(
          context: context,
          builder: (context) {
            return AlertDialog(
              title: Text('提示'),
              content: Text('您还未勾选同意说明'),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.pop(context);
                    return;
                  },
                  child: Text('确定'),
                ),
              ],
            );
          });
      return;
    }

    bool flag = true;
    if (speechLevel.text == '' ||
        speakerName.text == '' ||
        gender.text == '' ||
        speechTitle.text == '' ||
        speechDistrict.text == '' ||
        contestTraining.text == '' ||
        speechRank.text == '' ||
        nativeLanguage.text == '' ||
        (speechTags.text == '' &&
            !positive &&
            !negative &&
            !happyEnding &&
            !sadEnding &&
            !happyStart &&
            !sadStart &&
            !upAndDown)) {
      flag = false;
    } else {
      try {
        _speechVideoEntity.level = int.parse(speechLevel.text);
        _speechVideoEntity.speaker = speakerName.text;
        _speechVideoEntity.gender = int.parse(gender.text);
        _speechVideoEntity.title = speechTitle.text;
        _speechVideoEntity.district = speechDistrict.text;
        _speechVideoEntity.contest = contestTraining.text;
        _speechVideoEntity.rank = int.parse(speechRank.text);
        _speechVideoEntity.language = nativeLanguage.text;
      } catch (e) {
        Fluttertoast.showToast(msg: "level,gender,rank 只能为数字");
      }

      _speechVideoEntity.theme = theme;
      _speechVideoEntity.tags = [];
      if (positive) {
        _speechVideoEntity.tags.add("positive");
      }
      if (negative) {
        _speechVideoEntity.tags.add("negative");
      }
      if (happyEnding) {
        _speechVideoEntity.tags.add("happy ending");
      }
      if (sadEnding) {
        _speechVideoEntity.tags.add("sad ending");
      }
      if (happyStart) {
        _speechVideoEntity.tags.add("happy starting");
      }
      if (sadStart) {
        _speechVideoEntity.tags.add("sad starting");
      }
      if (upAndDown) {
        _speechVideoEntity.tags.add("ups and downs");
      }
      if (speechTags.text != '') {
        _speechVideoEntity.tags.add("${speechTags.text}");
      }

      //nativeLanguage
    }
    if (flag) {
      if (fileName != '') {
        if (file == null) {
          Fluttertoast.showToast(msg: "正在提交...");
          ResultEntity resultEntity = await api.updateSpeech(
              context.read<UserModel>().token, _speechVideoEntity);
          //
          if (resultEntity.code == 200) {
            Fluttertoast.showToast(msg: "提交成功");
          } else {
            Fluttertoast.showToast(msg: resultEntity.message);
          }
        } else {
          Fluttertoast.showToast(msg: "正在提交");
          final html.FormData formData = html.FormData()
            ..appendBlob('video', file);
          await html.HttpRequest.request(
              "http://120.53.230.49:8000/effective/speech/uploadVideo",
              method: 'POST',
              requestHeaders: {'token':context.read<UserModel>().token},
              sendData: formData, onProgress: (e) {

          }).then((httpRequest) {
            print(httpRequest.response.runtimeType);
            Map map = jsonDecode(httpRequest.response.toString());
            _speechVideoEntity.video = map['data'];
          });
          if (_speechVideoEntity.video == '') {
            Fluttertoast.showToast(msg: "文件上传失败");
          } else {
            ResultEntity resultEntity = await api.createSpeech(
                context.read<UserModel>().token, _speechVideoEntity);
            if (resultEntity.code == 200) {
              Fluttertoast.showToast(msg: "提交成功");
            } else {
              Fluttertoast.showToast(msg: resultEntity.message);
            }
          }
        }
      } else {
        Fluttertoast.showToast(msg: "请上传文件");
      }
    } else {
      Fluttertoast.showToast(msg: "请完善相关内容");
    }
  }

  Future loadData(BuildContext context) async {
    setState(ViewState.Busy);
    _speechVideoEntity = new SpeechVideoEntity();
    //数据加载
    if (Provider.of<UserModel>(context).token == "") {
      _speechVideoEntity = SpeechVideoEntity();
    } else {
      ResultEntity resultEntity =
          await api.getSpeech(Provider.of<UserModel>(context).token ?? "");
      if (resultEntity.code == 200) {
        _speechVideoEntity = SpeechVideoEntity().fromJson(resultEntity.data);
        speakerName.text = _speechVideoEntity.speaker;
        speechLevel.text = _speechVideoEntity.level.toString();
        gender.text = _speechVideoEntity.gender.toString();
        speechTitle.text = _speechVideoEntity.title;
        speechDistrict.text = _speechVideoEntity.district;
        contestTraining.text = _speechVideoEntity.contest;
        speechRank.text = _speechVideoEntity.rank.toString();
        nativeLanguage.text = _speechVideoEntity.language;
        theme = _speechVideoEntity.theme;
        for (String tag in _speechVideoEntity.tags) {
          switch (tag) {
            case "positive":
              positive = true;
              break;
            case "negative":
              negative = true;
              break;
            case "happy ending":
              happyEnding = true;
              break;
            case "sad ending":
              sadEnding = true;
              break;
            case "happy starting":
              happyStart = true;
              break;
            case "sad starting":
              sadStart = true;
              break;
            case "ups and downs":
              upAndDown = true;
              break;
            default:
              {
                speechTags.text = tag;
              }
          }
        }
        fileName = _speechVideoEntity.video
            .substring(_speechVideoEntity.video.lastIndexOf("/") + 1);
        notifyListeners();
      } else {
        _speechVideoEntity = new SpeechVideoEntity();
      }
    }

    setState(ViewState.Idle);
  }

  void reset() {
    theme = null;

    positive = false;
    negative = false;
    happyEnding = false;
    sadEnding = false;
    happyStart = false;
    sadStart = false;
    upAndDown = false;

    speechLevel.text = '';
    speakerName.text = '';
    gender.text = '';
    speechTitle.text = '';
    speechDistrict.text = '';
    contestTraining.text = '';
    speechLevel.text = '';
    speechRank.text = '';
    nativeLanguage.text = '';
    fileName = '';
    file = null;
    notifyListeners();
  }
}
